<?php
	/* The private calendar */
	class CalendarInviteController extends Zone_Action{

		public function initAction(){
			if(!$this->hasRole('calendar')){
				$this->removeLayout();
				$this->setContent(error('Bạn không được phép truy cập phân hệ này.'));	
				$this->stop();
			}
			
			$departments = $this	
				->Model
				->fetchAll("SELECT `a`.* 
					FROM `departments` as `a` 
					LEFT JOIN `departments` as `b`
						ON `a`.`parent_id`=`b`.`ID`
					LEFT JOIN `departments` as `c`
						ON `b`.`parent_id`=`c`.`ID`
					WHERE 
						`b`.`ID` IS NOT NULL AND `c`.`ID` IS NULL");
			$this->set('departments',$departments);	
		}		
		
		protected function getCalendar( $time, $date ){
			$user_id = get_user_id();
			return $this->Model->fetchAll("SELECT *
				FROM `calendars` as `a`
				LEFT JOIN `calendars_users` as `b`
					ON `a`.`ID`= `b`.`calendar_id` 
						AND `b`.`user_id`='$user_id' 
				WHERE 
					`a`.`is_draft`='no'
					AND `b`.`user_id`='$user_id' 
					AND `a`.`type`='user'
					AND `a`.`date_start` <= '$date'	
					AND (
						( `a`.`repeat_type`='none' AND `a`.`date_start`='$date'  )
						OR (
							( `a`.`repeat_date_end` IS NULL OR `a`.`repeat_date_end` >= '$date' )
							AND(
								( `a`.`repeat_type`='day' AND CONCAT(',',`a`.`repeat_day`,',') LIKE '%,".(date('N',$time)%7).",%' ) 
								OR ( `a`.`repeat_type`='week'  AND DAYOFWEEK(`a`.`date_start`)  = '".(date('N',$time)%7)."'  ) 
								OR ( `a`.`repeat_type`='month' AND DAYOFMONTH(`a`.`date_start`) = DAYOFMONTH('$date')  )
								OR ( `a`.`repeat_type`='year'  AND DAYOFMONTH(`a`.`date_start`) = DAYOFMONTH('$date') AND MONTH(`a`.`date_start`) = MONTH('$date') ) 
							)
						)		
					)	
				ORDER BY `a`.`time_start`");		
		}
				
		public function indexAction(){
			$date = get('date',date('Y-m-d'));
			$time = strtotime($date);
			$year = (int)get('year',$time);
			$week = (int)get('week',$time);
			
			$user_id = get_user_id();
			$posts = $this->getCalendar($time,$date);
			$this->set(array(
				posts	=> $posts,
				time	=> $time
			));			
		
		}
		
		public function listAction(){
			$user_id = get_user_id();
			$vars = array();
			$where = array();
			$order_by = "ORDER BY `a`.`ID` DESC";
			
			$current_page = max(getInt('p',1),1);		
			$range_page = max(10,(int)$this->getConfig('user.page',20));
			
			if( isset($_REQUEST['p']) ){
				$vars['p'] = $current_page;
			}
			
			$where[] ="`a`.`is_draft`='no'";
			$where[] ="`a`.`type`='user'";
			$where[] = "`b`.`user_id`='$user_id'";
			
			$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
					
			$field_order = array('title','created_by_id');
			foreach( $field_order as $f ){
				if( get('order_by') == $f ){
					$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
					$vars['order_by'] = $f;
					if( get('order_type') == 'desc' ){
						$vars['order_by']='desc';
					}
					break;	
				}	
			}		
			
			$total = $this->Model->fetchOne("SELECT COUNT(*) 
					FROM `calendars` as `a`
					LEFT JOIN `calendars_users` as `b`
						ON `a`.`ID`= `b`.`calendar_id` AND `b`.`user_id`='$user_id' 					
					WHERE ".implode(' AND ',$where));
					
			$posts = $this->Model->fetchAll("SELECT `a`.*
					,`c`.`username` as `created_by_name`
					,`c`.`is_deleted` as `created_is_deleted`
				FROM `calendars` as `a`	
				LEFT JOIN `calendars_users` as `b`
					ON `a`.`ID`= `b`.`calendar_id` 
						AND `b`.`user_id`='$user_id' 
				LEFT JOIN `users` as `c`
					ON `a`.`created_by_id`=`c`.`ID`
				WHERE ".implode(' AND ',$where)."
			$order_by $limit");
					
			$a = $vars;
			unset($a['p']);
			
			$page = page_ajax('#Calendar/Invite/List?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
				
			$this->set(array(
				page	=> $page,
				total	=> $total,
				vars	=> $vars,
				posts	=> $posts
			));		
		}	
		
		public function weekAction(){			
			$year = (int)get('year',date("Y",time()));
			$week = (int)get('week',(int)date("W",time()));
			$time = strtotime("{$year}W{$week}1");
			
			$days = array();
			$user_id = get_user_id();
			
			for( $i=1; $i <= 7; $i++ ){
				$ctime = strtotime("{$year}W{$week}{$i}");
				$cdate = date('Y-m-d', $ctime );
				
				$calendars = $this->getCalendar($ctime,$cdate);				
				$days[ $ctime ] = $calendars;				
			}
		
			$this->set(array(
				days	=> $days,
				time	=> $time
			));
		}

		public function monthAction(){			
			$year = (int)get('year',date("Y",time()));
			$month = (int)get('month',(int)date("m",time()));
			$time = strtotime("$year-$month-01");
			
			$months = array();
			$user_id = get_user_id();
			
			for( $i=1; $i <= 31; $i++ ){
				$ktime = mktime(0,0,0,$month,$i,$year);
				if( (int)date('m',$ktime) != $month ){
					break;
				}
				$date = date("Y-m-d",$ktime);
				$y = (int)date("Y",$ktime);
				$m = (int)date("m",$ktime);
				$d = (int)date("d",$ktime);
				
				
				$calendars = $this->getCalendar($ktime,$date);				
				$months["$y-$m-$d"] = $calendars;				
			}
		
			$this->set(array(
				months	=> $months,
				year	=> $year,
				month	=> $month,
				time	=> $time
			));
		}		
	
		/* view on popup */
		public function viewAction(){
			$calendar_id = get('ID',0);
			$user_id 	 = get_user_id();
			
			$post = $this
				->Model->fetchRow("SELECT 
						`a`.*,
						`u`.`username` as `updated_by_name`,
						`u`.`is_deleted` as `updated_is_deleted`
					FROM `calendars` as `a` 
					LEFT JOIN `calendars_users` as `b`
						ON `a`.`ID`=`b`.`calendar_id` AND `b`.`user_id`='$user_id'
					LEFT JOIN `users` as `u`
						ON `u`.`ID`=`a`.`updated_by_id`
					WHERE `a`.`is_draft`='no' 
						AND `a`.`ID`='$calendar_id'
						AND `b`.`calendar_id` IS NOT NULL");

			if( !$post ){
				return $this->setJSON(array(
					alert => 'Sự kiện không tồn tại hoặc bạn không được tham gia.'
				));			
			}
			
			if( isPost() ){
				/*if( ( 
						$post['repeat_type'] =='none' 
						&&
						strtotime("+1 days",$post['date_start']) <= time()
					)
					|| ( $post['repeat_date_end']
							&&
						 strtotime($post['repeat_date_end']) < time()	
						)
					){
					return $this->setJSON(array(
						message	=> error('Sự kiện này đã kết thúc.')
					));				
				}*/
				
				loadClass('ZData');
				$f = new ZData();
				$f->addField(array(
					status	=> array(
						type		=> 'ENUM',
						value		=> array('yes','no','waiting'),
						no_empty	=> 'yes'	
					),
					quote	=> array(
						type			=> 'TEXT',
						default_value	=> ''
					)
				));
				$data = $f->getData();
				if( !is_array($data) ){
					return $this->setJSON(array(
						message	=> error($data)
					));				
				}
				
				$this->Model->update('calendars_users',$data
					,"`user_id`='$user_id' AND `calendar_id`='$calendar_id'");					
				$this->setJSON(array(
					redirect	=> "#Calendar/Invite/View?ID=$calendar_id"
				));	
			}
						
			$guests = $this
				->Model->fetchAll("SELECT 
						`a`.*,
						`b`.`status` as `status`,
						`b`.`quote` as `quote`
					FROM `users` as `a` 
					LEFT JOIN `calendars_users` as `b`
						ON `b`.`user_id`=`a`.`ID` 
							AND `b`.`calendar_id`='$calendar_id'
					WHERE `b`.`calendar_id`='$calendar_id'");
					
			$this->set(array(
				post	=> $post,
				guests	=> $guests
			));
			
			
			
		}
	}
 ?>